#include "Renderer.h"

Renderer::Renderer(SDL_Surface* screen) {
	this->screen = screen;
	redKey = 0;
	greenKey = 0xFF;
	blueKey = 0xFF;
	centerX = centerY = 0;
}

void Renderer::applySurface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip) {
	SDL_Rect offset;
	offset.x = x;
	offset.y = y;
	if (destination == NULL && screen != NULL) {
		SDL_BlitSurface(source, clip, screen, &offset);
	}
	else {
		SDL_BlitSurface(source, clip, destination, &offset);
	}
}

void Renderer::setCenterPoint(int x, int y) {
	this->centerX = x;
	this->centerY = y;
}

SDL_Surface* Renderer::loadImage(std::string filename) {
	SDL_Surface* loadedImage = NULL;
	SDL_Surface* optimizedImage = NULL;

	loadedImage = IMG_Load(filename.c_str());
	if (loadedImage != NULL) {
		optimizedImage = SDL_DisplayFormat(loadedImage);
		SDL_FreeSurface(loadedImage);
		if (optimizedImage != NULL) {
			Uint32 colorKey = SDL_MapRGB(optimizedImage->format, redKey, greenKey, blueKey);
			SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorKey);
		}
	}
	return optimizedImage;
}

void Renderer::draw(Map* map) {
	int width = map->getMapWidth();
	int height = map->getMapHeight();

	for (int x = 0; x < width; x++) {
		for (int y = 0; y < height; y++) {
			Cell* cell = map->getCell(x, y);
			int xCoord = cell->getXTextCoord();
			int yCoord = cell->getYTextCoord();
			int cellWidth = map->getCellWidth();
			int cellHeight = map->getCellHeight();
			
			SDL_Rect rect = SDL_Rect();
			rect.h = cellHeight;
			rect.w = cellWidth;
			rect.x = cellWidth * xCoord;
			rect.y = cellHeight * yCoord;

			applySurface(x * cellWidth - centerX + screen->w / 2, y * cellHeight - centerY + screen->h / 2, map->getTileSheet(), screen, &rect);
		}
	}
}

void Renderer::draw(Renderable* entity) {
	SDL_Rect clip = entity->getClip();
	double x = entity->getXPos() - centerX;
	double y = entity->getYPos()- centerY;
	
	applySurface((int)x + screen->w / 2, (int)y + screen->h / 2, entity->getTexture(), screen, &clip);
}